<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Waveform Chart</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
<div id="main" style="width: 1200px;height:800px;"></div>
<button type="button" onclick="stopInterval()">停止</button>
<button type="button" onclick="startInterval()">开始</button>
<script src="https://cdn.bootcdn.net/ajax/libs/mqtt/4.1.0/mqtt.min.js"></script>
<script src="https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min.js"></script>
<!--<script src="data.js"></script>-->
<!--<script src="chartsData.js"></script>-->
<!--<script src="adata.js"></script>-->
<script src="mqtt.js"></script>
<script type="text/javascript">
  // const size = adata[1].length
  let param = {
    mb_h: [],
    mb_l: [],
    jy_h: [],
    jy_l: [],
    xData: new Array(1201).fill(''),
    mb: new Array(1201).fill(null),
    jy: new Array(1201).fill(null),
    currentIndex: 0,
    size: 0,
    intervalFlag: false
  }

  /*  adata[1].forEach(([first, second, third, fourth]) => {
     param.jy_l.push(first)
     param.jy_h.push(second)
     param.mb_l.push(third)
     param.mb_h.push(fourth)
   }) */
  var echartsOption = {
    color: ['#428DF9', '#95CEF3'],
    tooltip: {
      trigger: 'axis',
      formatter: function(t) {
        if (t) {
          let e = ''
          e += t[0].name.replace(/\-/g, '/') + '<br/>'
          for (let n = 0; n < t.length; n++) {
            const o = t[n]
            e += '<div>',
              e += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + o.color + ';"></span>',
              e += o.seriesName + '\uff1a' + o.value,
              e += '</div>'
          }
          return e
        }
      },
      backgroundColor: '#ccc',
      borderWidth: 1,
      borderColor: '#ccc',
      padding: 10,
      textStyle: {
        color: '#000',
        fontSize: 12,
        align: 'left'
      }
    },
    legend: {
      show: !0,
      x: 'center',
      y: '10px',
      data: [{
        name: '脉搏/强度&脉率',
        textStyle: {
          color: '#428DF9'
        }
      }, {
        name: '静压/深度',
        textStyle: {
          color: '#95CEF3'
        }
      }]
    },
    xAxis: {
      type: 'category',
      scale: !0,
      data: param.xData,
      axisTick: {
        alignWithLabel: !0
      },
      axisLine: {
        onZero: !1,
        lineStyle: {
          color: '#01efef'
        }
      },
      axisLabel: {
        textStyle: {
          color: '#01efef'
        }
      }
    },
    yAxis: [{
      type: 'value',
      name: '脉搏/强度&脉率',
      nameLocation: 'center',
      nameGap: 30,
      nameTextStyle: {
        color: '#428DF9'
      },
      axisLabel: {
        color: '#428DF9'
      },
      calculateMinMax: true,
      inverse: false, // 确保刻度顺序正确
      /* min: function(t) {
        if(t){
          return 1e3 * (Math.floor(t.min / 1e3) - 1)
        }
        return -2000   //-600
      },
      max: function(t) {
        if(t){

          return 1e3 * (Math.floor(t.max / 1e3) + 1)
        }
        return 3000     //600
      }, */
      splitLine: {
        show: !1
      }
    }, {
      type: 'value',
      name: '静压/深度',
      nameLocation: 'center',
      nameGap: 48,
      nameTextStyle: {
        color: '#95CEF3'
      },
      axisLabel: {
        color: '#95CEF3'
      },
      calculateMinMax: true,
      inverse: false, // 确保刻度顺序正确
      /* min: function(t) {
        if(t){
          return 1e3 * (Math.floor(t.min / 1e3) - 1)
        }
        //return 10000
      },
      max: function(t) {
        if(t){

          return 1e3 * (Math.floor(t.max / 1e3) + 1)
        }
        return 14000
      }, */
      splitLine: {
        show: !1
      }
    }],
    series: [param.mb, param.jy].map((e, n) => ({
      name: n === 0 ? '脉搏/强度&脉率' : '静压/深度',
      data: e,
      type: 'line',
      symbol: 'none',
      smooth: !0,
      yAxisIndex: n
    }))
  }
  var myChart = echarts.init(document.getElementById('main'))
  myChart.getZr().on('dblclick', params => {
    console.log('双击事件触发')
    if (param.intervalFlag) {
      stopInterval()
    } else {
      startInterval()
    }
  })
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(echartsOption)

  let interval
  startInterval()

  function startInterval() {
    interval = setInterval(() => {
      param.mb.shift()
      param.jy.shift()
      param.xData.shift()
      if (param.mb_l.length > 0) {
        param.mb.push(int16Overflow(param.mb_l.shift() + 256 * param.mb_h.shift()) / 10)
        param.jy.push(int16Overflow(param.jy_l.shift() + 256 * param.jy_h.shift()) * 10)
      } else if (param.mb_l.length <= 0) {
        param.mb.push(null)
        param.jy.push(null)
      }
      param.currentIndex++
      param.xData.push((0.005 * param.currentIndex).toFixed(3) + 's')
      myChart.setOption({
        series: [param.mb, param.jy].map((e, n) => ({
          data: e
        })),
        xAxis: {
          data: param.xData
        }
      })
      param.intervalFlag = true
    }, 5)
  }

  function startInterval1() {
    interval = setInterval(() => {
      param.mb.shift()
      param.jy.shift()
      param.xData.shift()
      if (param.currentIndex < param.size) {
        param.mb.push(int16Overflow(param.mb_l[param.currentIndex] + 256 * param.mb_h[param.currentIndex]) / 10)
        param.jy.push(int16Overflow(param.jy_l[param.currentIndex] + 256 * param.jy_h[param.currentIndex]) * 10)
      } else if (param.currentIndex >= param.size && param.currentIndex - param.size < 1201) {
        param.mb.push(null)
        param.jy.push(null)
      } else {
        stopInterval()
        return
      }
      param.currentIndex++
      param.xData.push((0.005 * param.currentIndex).toFixed(3) + 's')
      myChart.setOption({
        series: [param.mb, param.jy].map((e, n) => ({
          data: e
        })),
        xAxis: {
          data: param.xData
        }
      })
    }, 5)
  }

  function int16Overflow(num) {
    let result = num & 0xFFFF // 使用按位与运算符将数字限制在16位范围内
    if (result > 32767) { // 如果结果大于32767（int16的最大值）
      result -= 65536 // 减去65536以实现溢出
    } else if (result < -32768) { // 如果结果小于-32768（int16的最小值）
      result += 65536 // 加上65536以实现溢出
    }
    return result
  }

  function startInterval1() {
    interval = setInterval(() => {
      param.mb.shift()
      param.jy.shift()
      param.xData.shift()
      if (param.currentIndex < data.length) {
        param.mb.push(data[param.currentIndex].mb)
        param.jy.push(data[param.currentIndex].jy)
      } else if (param.currentIndex >= data.length && param.currentIndex - data.length < 1201) {
        param.mb.push(null)
        param.jy.push(null)
      } else {
        stopInterval()
        return
      }
      param.currentIndex++
      param.xData.push((0.005 * param.currentIndex).toFixed(3) + 's')
      myChart.setOption({
        series: [param.mb, param.jy].map((e, n) => ({
          data: e
        })),
        xAxis: {
          data: param.xData
        }
      })
    }, 5)
  }

  function stopInterval() {
    clearInterval(interval)
    param.intervalFlag = false
  }

  // 当客户端收到一个发布过来的消息时触发回调
  /**
   * topic：收到的报文的topic
   * message：收到的数据包的负载playload
   * packet：MQTT 报文信息，其中包含 QoS、retain 等信息
   */
  client.on('message', function(topic, message, packet) {
    // 这里有可能拿到的数据格式是Uint8Array格式，可以直接用toString转成字符串
    // let data = JSON.parse(message.toString());
    /*   console.log("获取到的数据：", message)
      console.log("数据对应订阅主题：", topic)
      console.log("获取到的数据包：", packet) */
    const jsonString = new TextDecoder().decode(message)

// 将字符串解析为JSON对象
    const jsonObject = JSON.parse(jsonString)
    jsonObject[1].forEach(([first, second, third, fourth]) => {
      param.jy_l.push(first)
      param.jy_h.push(second)
      param.mb_l.push(third)
      param.mb_h.push(fourth)
    })
  })
</script>
</body>
</html>
